﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using NetDon.OA.Data.CollectionClasses;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Data.HelperClasses;
using NetDon.OA.Data.Linq;
using NetDon.OA.Interface;
using NetDon.OA.Interface.Common;
using NetDon.Utilities;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace NetDon.OA.Business.Common
{
    public class ShuntingCostConfigService : IShuntingCostConfigService
    {

        public void AppendShuntingCostConfig(Guid areaId, Guid routeTypeId, string deliveryCity, string province )
        {
            if (!CheckShuntingCostConfigDataExists(Guid.Empty, routeTypeId, deliveryCity, areaId, (int)CheckoutType.Actual))
            {
                AddShuntingCostConfig(new ShuntingCostConfigData()
                {
                    AreaId = areaId,
                    RouteTypeId = routeTypeId,
                    DeliveryProvince = province,
                    DeliveryCity = deliveryCity,
                    CheckoutType = CheckoutType.Actual,
                    ShuntingCost =0,
                    UnitCost =0
                });
            }
            if (!CheckShuntingCostConfigDataExists(Guid.Empty, routeTypeId, deliveryCity, areaId, (int)CheckoutType.LessThanCarLoad))
            {
                AddShuntingCostConfig(new ShuntingCostConfigData()
                {
                    AreaId = areaId,
                    RouteTypeId = routeTypeId,
                    DeliveryProvince = province,
                    DeliveryCity = deliveryCity,
                    CheckoutType = CheckoutType.LessThanCarLoad,
                    ShuntingCost = 0,
                    UnitCost = 0
                });
            }
            if (!CheckShuntingCostConfigDataExists(Guid.Empty, routeTypeId, deliveryCity, areaId, (int)CheckoutType.Whole))
            {
                AddShuntingCostConfig(new ShuntingCostConfigData()
                {
                    AreaId = areaId,
                    RouteTypeId = routeTypeId,
                    DeliveryProvince = province,
                    DeliveryCity = deliveryCity,
                    CheckoutType = CheckoutType.Whole,
                    ShuntingCost = 0,
                    UnitCost = 0
                });
            }
        }

        public bool AddShuntingCostConfig(ShuntingCostConfigData shuntingCostConfigData)
        {
            var entity = ConvertToEntityByBusinessData(shuntingCostConfigData, true);
            return entity.Save();
        }

        public bool ModifyShuntingCostConfig(ShuntingCostConfigData shuntingCostConfigData)
        {
            var entity = ConvertToEntityByBusinessData(shuntingCostConfigData, false);
            return entity.Save();
        }

        public bool RemoveShuntingCostConfig(Guid shuntingCostConfigId)
        {
            var attachmentsCollection = new ShuntingCostConfigCollection();
            int result = attachmentsCollection.DeleteMulti(ShuntingCostConfigFields.Id == shuntingCostConfigId);
            return result > 0;
        }

        public ShuntingCostConfigData GetShuntingCostConfigById(Guid shuntingCostConfigId)
        {
            var meta = new LinqMetaData();
            var linqResult = (from q in meta.ShuntingCostConfig
                              where q.Id == shuntingCostConfigId
                              select q).FirstOrDefault();

            if (linqResult != null)
            {
                return ConvertToBusinessDataByEntity(linqResult);
            }

            return null;
        }

        public List<ShuntingCostConfigData> GetShuntingCostConfigs()
        {
            var meta = new LinqMetaData();
            var listResult = from q in meta.ShuntingCostConfig
                             select q;
            var listAttachments = new List<ShuntingCostConfigData>();
            if (listResult != null && listResult.Count() > 0)
            {
                foreach (var attachmentsEntity in listResult)
                {
                    var obj = ConvertToBusinessDataByEntity(attachmentsEntity);
                    if (obj != null)
                    {
                        listAttachments.Add(obj);
                    }
                }
            }

            return listAttachments;
        }

        public bool CheckShuntingCostConfigReferenced(Guid shuntingCostConfigId)
        {
            //var shuntingCostConfigEntity = new ShuntingCostConfigEntity(shuntingCostConfigId);
            //var meta = new LinqMetaData();
            //var linqResult = (from q in meta.IssuingOrder
            //                  where q.AreaId == shuntingCostConfigEntity.AreaId && q.DeliveryCity == shuntingCostConfigEntity.DeliveryCity && q.RouteTypeId == shuntingCostConfigEntity.RouteTypeId && q.CheckoutType == shuntingCostConfigEntity.CheckoutType
            //                  select q).Count();
            //return linqResult > 0;
            return true;

        }

        private ShuntingCostConfigEntity ConvertToEntityByBusinessData(ShuntingCostConfigData routeData, bool isAdd)
        {
            ShuntingCostConfigEntity entity = null;
            if (isAdd)
            {
                entity = new ShuntingCostConfigEntity();
                entity.Id = routeData.Id;
                if (entity.Id == Guid.Empty)
                {
                    entity.Id = Guid.NewGuid();
                }
            }
            else
            {
                entity = new ShuntingCostConfigEntity(routeData.Id);
            }
            entity.AreaId = routeData.AreaId;
            entity.RouteTypeId = routeData.RouteTypeId;
            entity.DeliveryCity = routeData.DeliveryCity;
            entity.CheckoutType = (int)routeData.CheckoutType;

            entity.ShuntingCost = routeData.ShuntingCost;
            entity.UnitCost = routeData.UnitCost;
            entity.DeliveryProvince = routeData.DeliveryProvince;


            return entity;
        }

        private ShuntingCostConfigData ConvertToBusinessDataByEntity(ShuntingCostConfigEntity routeEntity)
        {
            return new ShuntingCostConfigData
                       {
                           Id = routeEntity.Id,
                           AreaId = routeEntity.AreaId,
                           DeliveryCity = routeEntity.DeliveryCity,
                           RouteTypeId = routeEntity.RouteTypeId,
                           ShuntingCost = routeEntity.ShuntingCost,
                           UnitCost = routeEntity.UnitCost,
                           CheckoutType = EnumUtilities.Parse<CheckoutType>(routeEntity.CheckoutType.ToString()),
                           DeliveryProvince = routeEntity.DeliveryProvince
                       };
        }


        public int GetShuntingCostConfigCount(ShuntingCostConfigDataSearchCriteria criteria)
        {

            var collection = new ShuntingCostConfigCollection();
            return collection.GetDbCount(GetSearchShuntingCostConfigDataPredicate(criteria));
        }

        public IEnumerable<ShuntingCostConfigData> SearchShuntingCostConfigDatasByCondition(ShuntingCostConfigDataSearchCriteria criteria, string sortExpression, System.Web.UI.WebControls.SortDirection sortDirection, int pageSize, int pageIndex)
        {

            var sort = GetSortExpression(sortExpression, sortDirection);
            var collection = new ShuntingCostConfigCollection();
            collection.GetMulti(GetSearchShuntingCostConfigDataPredicate(criteria), 0, sort,
                              null, pageIndex + 1, pageSize);

            var result = from customerInfo in collection
                         select ConvertToBusinessDataByEntity(customerInfo);


            return result;
        }

        public ShuntingCostConfigData GetShuntingCostConfigDatasByCondition(ShuntingCostConfigDataSearchCriteria criteria)
        {
            var collection = new ShuntingCostConfigCollection();
            collection.GetMulti(GetSearchShuntingCostConfigDataPredicate(criteria));
           return ( from customerInfo in collection
                         select ConvertToBusinessDataByEntity(customerInfo)).FirstOrDefault();
        }

        private SortExpression GetSortExpression(string strInput, SortDirection sortDirection)
        {
            SortExpression sort;
            switch (strInput)
            {
                case "RouteTypeId":
                    sort = new SortExpression(ShuntingCostConfigFields.RouteTypeId | (SortOperator)(int)sortDirection);
                    break;
                case "DeliveryCity":
                    sort = new SortExpression(ShuntingCostConfigFields.DeliveryCity | (SortOperator)(int)sortDirection);
                    break;
                case "CheckoutType":
                    sort = new SortExpression(ShuntingCostConfigFields.CheckoutType | (SortOperator)(int)sortDirection);
                    break;

                case "UnitCost":
                    sort = new SortExpression(ShuntingCostConfigFields.UnitCost | (SortOperator)(int)sortDirection);
                    break;
                case "ShuntingCost":
                    sort = new SortExpression(ShuntingCostConfigFields.ShuntingCost | (SortOperator)(int)sortDirection);
                    break;
                default:
                    sort = new SortExpression
                               {
                                   ShuntingCostConfigFields.RouteTypeId | SortOperator.Ascending
                               };
                    break;

            }
            return sort;
        }

        private IPredicate GetSearchShuntingCostConfigDataPredicate(ShuntingCostConfigDataSearchCriteria criteria)
        {
            var expression = new PredicateExpression();
            if (!string.IsNullOrEmpty(criteria.DeliveryCity))
            {
                expression.Add(ShuntingCostConfigFields.DeliveryCity % ("%" + criteria.DeliveryCity + "%"));
            }

            if (criteria.RouteTypeId.HasValue && criteria.RouteTypeId.Value != Guid.Empty)
            {
                expression.Add(ShuntingCostConfigFields.RouteTypeId == criteria.RouteTypeId);
            }

            //if (criteria.AreaId.HasValue && criteria.AreaId.Value != Guid.Empty)
            //{
            //    expression.Add(ShuntingCostConfigFields.AreaId == criteria.AreaId);
            //}
            if (criteria.CheckoutType.HasValue)
            {
                expression.Add(ShuntingCostConfigFields.CheckoutType == criteria.CheckoutType.Value);
            }
            return expression;
        }


        public bool CheckShuntingCostConfigDataExists(Guid id, Guid routeType, string city, Guid areaId ,int checkoutType)
        {
            var meta = new LinqMetaData();
            bool exist = false;
            if (id != Guid.Empty)
            {
                //update check
                exist = meta.ShuntingCostConfig.Any(a => a.Id != id && a.RouteTypeId == routeType && a.AreaId == areaId && a.DeliveryCity == city && a.CheckoutType == checkoutType);
            }
            else
            {
                //add check
                exist = meta.ShuntingCostConfig.Any(a => a.RouteTypeId == routeType && a.AreaId == areaId && a.DeliveryCity == city && a.CheckoutType == checkoutType);
            }
            return exist;
        }
    }
}
